import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:logger/logger.dart';

import '../../models/user.dart';
import '../../services/user_service.dart';
import '../../state/auth_provider.dart';
import '../../core/app_config.dart';
import 'user_form_screen.dart';

/// 用户管理界面
class UserManagementScreen extends StatefulWidget {
  const UserManagementScreen({super.key});

  @override
  State<UserManagementScreen> createState() => _UserManagementScreenState();
}

class _UserManagementScreenState extends State<UserManagementScreen> {
  final UserService _userService = UserService();
  final Logger _logger = Logger();
  
  List<User> _users = [];
  bool _isLoading = false;
  String? _errorMessage;
  String _searchKeyword = '';

  @override
  void initState() {
    super.initState();
    _loadUsers();
  }

  /// 加载用户列表
  Future<void> _loadUsers() async {
    _logger.d('🔍 开始加载用户列表');
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final users = await _userService.getAllUsers();
      _logger.i('✅ 用户列表加载成功: ${users.length} 个用户');
      
      setState(() {
        _users = users;
        _isLoading = false;
      });
    } catch (e) {
      _logger.e('❌ 加载用户列表失败: $e');
      setState(() {
        _errorMessage = '加载用户列表失败: $e';
        _isLoading = false;
      });
    }
  }

  /// 搜索用户
  Future<void> _searchUsers(String keyword) async {
    _logger.d('🔍 开始搜索用户: keyword=$keyword');
    setState(() {
      _isLoading = true;
      _searchKeyword = keyword;
    });

    try {
      List<User> users;
      if (keyword.isEmpty) {
        users = await _userService.getAllUsers();
      } else {
        users = await _userService.searchUsers(keyword);
      }
      
      _logger.i('✅ 用户搜索成功: 找到 ${users.length} 个用户');
      
      setState(() {
        _users = users;
        _isLoading = false;
      });
    } catch (e) {
      _logger.e('❌ 搜索用户失败: $e');
      setState(() {
        _errorMessage = '搜索用户失败: $e';
        _isLoading = false;
      });
    }
  }

  /// 删除用户
  Future<void> _deleteUser(User user) async {
    _logger.d('🗑️ 开始删除用户: ${user.username}');
    
    // 确认对话框
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除用户 "${user.displayName}" 吗？此操作不可恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

    try {
      final success = await _userService.deleteUser(user.id!);
      if (success) {
        _logger.i('✅ 用户删除成功: ${user.username}');
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('用户 "${user.displayName}" 已删除')),
        );
        _loadUsers(); // 重新加载列表
      } else {
        _logger.w('❌ 用户删除失败: ${user.username}');
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('删除用户失败，请重试')),
        );
      }
    } catch (e) {
      _logger.e('❌ 删除用户异常: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('删除用户失败: $e')),
      );
    }
  }

  /// 切换用户状态
  Future<void> _toggleUserStatus(User user) async {
    _logger.d('🔄 开始切换用户状态: ${user.username}');
    
    try {
      final success = await _userService.toggleUserStatus(user.id!);
      if (success) {
        _logger.i('✅ 用户状态切换成功: ${user.username}');
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('用户 "${user.displayName}" 状态已更新')),
        );
        _loadUsers(); // 重新加载列表
      } else {
        _logger.w('❌ 用户状态切换失败: ${user.username}');
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('更新用户状态失败，请重试')),
        );
      }
    } catch (e) {
      _logger.e('❌ 切换用户状态异常: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('更新用户状态失败: $e')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('用户管理'),
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () => _showUserForm(context),
            tooltip: '添加用户',
          ),
        ],
      ),
      body: Column(
        children: [
          // 搜索栏
          _buildSearchBar(),
          
          // 错误信息显示
          if (_errorMessage != null) _buildErrorDisplay(),
          
          // 用户列表
          Expanded(child: _buildUserList()),
        ],
      ),
    );
  }

  /// 构建搜索栏
  Widget _buildSearchBar() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: TextField(
        decoration: InputDecoration(
          hintText: '搜索用户...',
          prefixIcon: const Icon(Icons.search),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(AppConfig.defaultRadius),
          ),
        ),
        onChanged: (value) {
          // 防抖搜索
          Future.delayed(const Duration(milliseconds: 300), () {
            if (mounted) {
              _searchUsers(value);
            }
          });
        },
      ),
    );
  }

  /// 构建错误信息显示
  Widget _buildErrorDisplay() {
    return Container(
      width: double.infinity,
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Color(AppConfig.warningColor).withOpacity(0.1),
        borderRadius: BorderRadius.circular(AppConfig.defaultRadius),
        border: Border.all(
          color: Color(AppConfig.warningColor).withOpacity(0.3),
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.error_outline,
            color: Color(AppConfig.warningColor),
            size: 20,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              _errorMessage!,
              style: TextStyle(color: Color(AppConfig.warningColor)),
            ),
          ),
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _loadUsers,
            color: Color(AppConfig.warningColor),
          ),
        ],
      ),
    );
  }

  /// 构建用户列表
  Widget _buildUserList() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_users.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.people_outline,
              size: 64,
              color: Color(AppConfig.textSecondaryColor),
            ),
            const SizedBox(height: 16),
            Text(
              _searchKeyword.isEmpty ? '暂无用户' : '未找到匹配的用户',
              style: TextStyle(
                fontSize: 16,
                color: Color(AppConfig.textSecondaryColor),
              ),
            ),
          ],
        ),
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: _users.length,
      itemBuilder: (context, index) {
        final user = _users[index];
        return _buildUserCard(user);
      },
    );
  }

  /// 构建用户卡片
  Widget _buildUserCard(User user) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      child: ListTile(
        leading: CircleAvatar(
          backgroundColor: user.isActive 
              ? Color(AppConfig.primaryColor)
              : Color(AppConfig.textSecondaryColor),
          child: Text(
            user.displayName.substring(0, 1).toUpperCase(),
            style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
          ),
        ),
        title: Text(
          user.displayName,
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: user.isActive 
                ? Color(AppConfig.textPrimaryColor)
                : Color(AppConfig.textSecondaryColor),
          ),
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('用户名: ${user.username}'),
            Text('角色: ${user.roleName}'),
            if (user.email != null) Text('邮箱: ${user.email}'),
            Text(
              '状态: ${user.isActive ? "启用" : "禁用"}',
              style: TextStyle(
                color: user.isActive 
                    ? Color(AppConfig.accentColor)
                    : Color(AppConfig.warningColor),
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
        trailing: PopupMenuButton<String>(
          onSelected: (value) => _handleUserAction(value, user),
          itemBuilder: (context) => [
            const PopupMenuItem(
              value: 'edit',
              child: Row(
                children: [
                  Icon(Icons.edit),
                  SizedBox(width: 8),
                  Text('编辑'),
                ],
              ),
            ),
            PopupMenuItem(
              value: 'toggle_status',
              child: Row(
                children: [
                  Icon(user.isActive ? Icons.block : Icons.check_circle),
                  const SizedBox(width: 8),
                  Text(user.isActive ? '禁用' : '启用'),
                ],
              ),
            ),
            if (!user.isAdmin) PopupMenuItem(
              value: 'delete',
              child: const Row(
                children: [
                  Icon(Icons.delete, color: Colors.red),
                  SizedBox(width: 8),
                  Text('删除', style: TextStyle(color: Colors.red)),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 处理用户操作
  void _handleUserAction(String action, User user) {
    switch (action) {
      case 'edit':
        _showUserForm(context, user: user);
        break;
      case 'toggle_status':
        _toggleUserStatus(user);
        break;
      case 'delete':
        _deleteUser(user);
        break;
    }
  }

  /// 显示用户表单
  void _showUserForm(BuildContext context, {User? user}) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => UserFormScreen(user: user),
      ),
    ).then((_) {
      // 返回后重新加载用户列表
      _loadUsers();
    });
  }
} 